package cn.xkai.exercise.b;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @description: 路径总和
 * @author: kaixiang
 * @date: 2022/7/16
 **/
public class Solution68 {
    public boolean hasPathSum(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null) {
            return root.val == targetSum;
        }
        return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
    }

    public boolean hasPathSumStack(TreeNode root, int targetSum) {
        if (root == null) {
            return false;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur  = stack.pop();
            if (cur.left == null && cur.right == null) {
                if (cur.val == targetSum) {
                    return true;
                }
            }
            if (cur.left != null) {
                cur.left.val = cur.val + cur.left.val;
                stack.push(cur.left);
            }
            if (cur.right != null) {
                cur.right.val = cur.val + cur.right.val;
                stack.push(cur.right);
            }
        }
        return false;
    }

    public boolean hasPathSumBFS(TreeNode root, int sum) {
        if (root == null)
            return false;
        Queue<TreeNode> queue = new LinkedList<>();
        root.val = sum - root.val;
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            //累减到根节点之后，结果为0，说明存在这样一条路径，直接返回true
            if (node.left == null && node.right == null && node.val == 0)
                return true;
            //左子节点累减
            if (node.left != null) {
                node.left.val = node.val - node.left.val;
                queue.add(node.left);
            }
            //右子节点累减
            if (node.right != null) {
                node.right.val = node.val - node.right.val;
                queue.add(node.right);
            }
        }
        return false;
    }

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
